package top.luo.sqlSession;

import top.luo.pojo.Configuration;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author luo
 * @date 2021-01-04 21:45
 */
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        return executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> list = selectList(statementId, params);
        if (list.size() == 1) {
            return (T) list.get(0);
        } else {
            throw new RuntimeException("more than one row");
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        // jdk动态代理生成mapper代理对象
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 根据不同情况，调用不用的session方法(selectList, selectOne等)

                // 参数1 stamentId(mapperClass.method), 参数2 params: args
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();
                String statementId = className + "." + methodName;

                // 获取被调用方法的返回值类型
                Type returnType = method.getGenericReturnType();

                // 是否进行了泛型类型参数化
                if (returnType instanceof ParameterizedType) {
                    return selectList(statementId, args);
                }

                return selectOne(statementId, args);

            }
        });

        return (T) proxyInstance;
    }

}
